from collections import OrderedDict

from apps.goods.models import GoodsChannel
def get_categories():
    #1.三级商品分类获取
    #1.1 获取所有频道表37个数据
    channels = GoodsChannel.objects.order_by("group_id","sequence")
    categories = OrderedDict()
    for channel in channels:
        #1.2根据频道 获取 组——id
        group_id = channel.group_id
        #1.3判断 如果 字典里面 有 组——id  不在生成新的字典
        if group_id not in categories:
            categories[group_id] = {"channels":[],"sub_cats":[]}

        #1.4根据频道 获取一级分类 category 外键属性

        # 一级分类  需要  多加一个key --url--频道表
        cat1 = channel.category
        #动态添加属性
        cat1.url = channel.url
        categories[group_id]["channels"].append(cat1)
        #1.5 处理二级  三级 分类 cat1.subs.all()  cat2.subs.all()
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]["sub_cats"].append(cat2)
    return categories